package net.huashitong.ssydt.provider.task.service;

import net.huashitong.ssydt.base.dao.LongMapper;
import net.huashitong.ssydt.base.service.AbstractLongService;
import net.huashitong.ssydt.provider.task.mapper.SsTaskMedalRecordMapper;
import net.huashitong.ssydt.task.entity.SsTaskMedal;
import net.huashitong.ssydt.task.entity.SsTaskMedalRecord;
import net.huashitong.ssydt.task.entity.SsTaskMyMedal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

import static net.huashitong.ssydt.task.constant.TaskConsts.MAX_MEDAL_SCORE;


/**
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2018.01.11
 */
@Service
@Transactional
public class SsTaskMedalRecordServiceImpl extends AbstractLongService<SsTaskMedalRecord> implements SsTaskMedalRecordService {

    private SsTaskMedalRecordMapper mapper;

    private SsTaskMyMedalService ssTaskMyMedalService;

    private SsTaskMedalService ssTaskMedalService;

    @Autowired
    public SsTaskMedalRecordServiceImpl(SsTaskMedalRecordMapper mapper,
                                        SsTaskMyMedalService ssTaskMyMedalService,
                                        SsTaskMedalService ssTaskMedalService) {
        this.mapper = mapper;
        this.ssTaskMyMedalService = ssTaskMyMedalService;
        this.ssTaskMedalService = ssTaskMedalService;
    }

    @Override
    protected LongMapper<SsTaskMedalRecord> getLongMapper() {
        return this.mapper;
    }

    @Override
    public List<SsTaskMedalRecord> findByUserId(String userId) {
        return this.mapper.findByUserId(userId);
    }

    @Override
    public SsTaskMedalRecord getByUserIdWidthMedalId(String userId, Long medalId) {
        SsTaskMedalRecord record = new SsTaskMedalRecord();
        record.setUserId(userId);
        record.setMedalId(medalId);
        return this.mapper.getByUserIdWidthMedalId(record);
    }

    @Override
    public void saveAndUpdateMyMedal(SsTaskMedalRecord medalRecord) {
        this.insert(medalRecord);
        //更新我的勋章
        SsTaskMyMedal ssTaskMyMedal = ssTaskMyMedalService.getAutoCreateByUserId(medalRecord.getUserId());
        ssTaskMyMedal.setMedalNumber(ssTaskMyMedal.getMedalNumber() + 1);
        if (ssTaskMyMedal.getAddScore().compareTo(MAX_MEDAL_SCORE) < 0) {
            SsTaskMedal ssTaskMedal = ssTaskMedalService.selectByPrimaryKey(medalRecord.getMedalId());
            BigDecimal addScore = ssTaskMyMedal.getAddScore().add(ssTaskMedal.getExtraScore());
            if (addScore.compareTo(MAX_MEDAL_SCORE) > 0) {
                addScore = MAX_MEDAL_SCORE;
            }
            ssTaskMyMedal.setAddScore(addScore);
        }
        ssTaskMyMedalService.updateByPrimaryKey(ssTaskMyMedal);
    }
}
